﻿
<!DOCTYPE html>
<html>
<head>
	<title>问卷答题</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
<link rel="stylesheet" type="text/css" href="/framework/vue/weui.min.css">
<link rel="stylesheet" type="text/css" href="/system/views/wenjuan/wenjuan.css">
<style type="text/css">
table td
{
    width:5rem;
}
</style>
</head>
<body>
<header id="appshow" style="display:none;top: 0;position: fixed;right: 0;left: 0;z-index: 10;height: 2.5rem;padding-right: .5rem;padding-left: .5rem;background-color: #f7f7f8;border-bottom: 1px solid #e7e7e7;-webkit-backface-visibility: hidden;backface-visibility: hidden;">
    <a onclick="location.href='/app/home.html'" style="top: 0;height: 2.2rem; padding: 0 10px 0 0;font-size: 1.5rem; font-weight: bold;line-height: 2.5rem;color: #0894ec;border: 0;float: left;">
            <span class="icon  iconfont icon-shangyiye2"></span>&lt; 
    </a>
    <h1 style="display: block; width: 100%;padding: 0;margin: 0 -.5rem;font-size: 1rem;font-weight: 500;line-height: 2.5rem;color: #3d4145;text-align: center;white-space: nowrap;">问卷调研</h1>
</header>
<div id="app" style="padding: 0" >

<div class="container" v-if="!jieshu" style=" padding:1rem;">


<h1>{{wjobj.title}}</h1>

	{{wjobj.hi}}

<div v-for="(groupobj,index) in wjobj.question" :key="groupobj.id" v-if="wjobj.type!=3"><!--遍历题题目分组-->
	<div class="weui-loadmore weui-loadmore_line">
	            <span class="weui-loadmore__tips">{{groupobj.groupname}}</span>
	</div>


	<!--遍历题目-->
	<div v-for="(questionobj,xuhao) in groupobj.group" class="danti" :key="questionobj.id">
		<font color="red" v-if="questionobj.qmust">*</font><span v-html="xuhao+1"></span>{{tixingname(questionobj.qtype) }} {{questionobj.qtitle}}
		<ol type="A">
			<li v-for="(xuanxiang,abc) in questionobj.qselection" :id="xuanxiang.id" :key="xuanxiang.id" v-if="questionobj.qtype == 0 || questionobj.qtype == 1" 
			@click="xuanze(groupobj.id,questionobj.id,questionobj.qtype,xuanxiang)">


			<input type="checkbox" :id="'K'+xuanxiang.id" :name="questionobj.id" class="regular-checkbox" :checked="answers(groupobj.id,questionobj.id,xuanxiang.id)" v-if="questionobj.qtype==1"  disabled="disabled" /><label :for="'K'+xuanxiang.id" v-if="questionobj.qtype==1"></label>

			<input type="radio" :id="'K'+xuanxiang.id" :name="questionobj.id" :checked="answers(groupobj.id,questionobj.id,xuanxiang.id)" class="regular-radio"  v-if="questionobj.qtype==0" /><label :for="'K'+xuanxiang.id" v-if="questionobj.qtype==0"></label>


			 {{xuanxiang.text}}
        <div v-if="baobiao" style="width: 200px; border: 1px #eee solid; background-color: #fff; float: right; margin-top: 5px;" > <div style=" background-color: #39f;" :style="{width:(xuanxiang.selected/jindutiao(xuanxiang.selected,questionobj.id)*100)+'%'}">{{xuanxiang.selected}}</div></div>
			</li>
			
			
			<textarea class="weui-textarea" :id="'text'+questionobj.id" placeholder="请输入文本" rows="3" v-if="questionobj.qtype == 2 && !baobiao" @blur="xuanze(groupobj.id,questionobj.id,questionobj.qtype)" ></textarea><br />

      <a href="javascript;"  v-if="questionobj.qtype == 2 && baobiao&&questionobj.answerlist==undefined" @click="findAnswer(questionobj,questionobj.id)" class="weui-btn weui-btn_mini weui-btn_default">查看答案</a>


		
             
             <table  v-if="questionobj.qtype == 3">
                <tr>
                    <td  v-for="(xuanxiang,abc) in questionobj.qselection"  track-by="_text">
                        <span>
                            <input type="radio" :id="'K'+xuanxiang.id" :name="questionobj.id" class="regular-radio" :value="xuanxiang.text" :checked="answers(groupobj.id,questionobj.id,xuanxiang.id)"  /> 
                            <label :for="'K'+xuanxiang.id" @click="xuanze(groupobj.id,questionobj.id,questionobj.qtype,xuanxiang);"></label> 
                            {{xuanxiang.text}} 
                            <div v-if="baobiao" style="width: 200px; border: 1px #eee solid; background-color: #fff; float: right; margin-top: 5px;" >
                            <div style=" background-color: #39f;" :style="{width:(xuanxiang.selected/jindutiao(xuanxiang.selected,questionobj.id)*100)+'%'}">{{xuanxiang.selected}}</div>
                            </div> 
                        </span>
                    </td>
                </tr>
             </table>
		</ol>
	</div>



</div>














<!-- loading toast -->
    <div id="loadingToast" v-if="loading">
        <div class="weui-mask_transparent"></div>
        <div class="weui-toast">
            <i class="weui-loading weui-icon_toast"></i>
            <p class="weui-toast__content">数据加载中</p>
        </div>
    </div>



<a href="javascript:;" class="weui-btn weui-btn_primary" @click="sumberjuan()" v-if="!baobiao&&wjobj.type!=3"  style="margin-top: 2rem;">提交问卷</a>
<a href="javascript:;" id="saveUserMark" class="weui-btn weui-btn_primary" @click="saveUserMark()" v-if="!baobiao&&wjobj.type==3"  style="margin-top: 2rem;">保存评价</a>
</div>





<div class="page msg_success js_show" v-if="jieshu">
    <div class="weui-msg">
        <div class="weui-msg__icon-area" v-if="wjobj.type != 2"><i class=" weui-icon_msg" v-if="wjobj.qualified !=null" :class="wjobj.qualified.min>sums?'weui-icon-warn':'weui-icon-success'"></i>

        <i class=" weui-icon_msg weui-icon-success" v-if="wjobj.qualified ==null" ></i>
        </div>
        <div class="weui-msg__text-area" v-if="wjobj.type != 2">
            <h2 class="weui-msg__title">提交成功</h2>
            <p class="weui-msg__desc" v-html="wjobj.end"></p>
        </div>

       <div class="weui-panel weui-panel_access"  v-if="wjobj.type == 2" style="margin-bottom: 50px;">
            <div class="weui-panel__hd">测评结果</div>
            <div class="weui-panel__bd">
                <div class="weui-media-box weui-media-box_text" v-for="jg in wjobj.result" v-if="sums >=jg.sectionmin && sums <=jg.sectionmax">
                    <h4 class="weui-media-box__title">{{jg.name}}</h4>
                    <p class="weui-media-box__desc">{{jg.describe}}</p>
                </div>
  
            </div>
        </div>
        
    </div>
</div>

</div>

<div class="weui-footer">
    <p class="weui-footer__text">Copyright © </p>
</div>
<div id="laod" style="position: fixed; top:0;left: 0; width: 100%; height: 100%; background-color: #eee; text-align: center; padding-top: 100px;">
	<i class="weui-loading weui-icon_toast"></i><br>
	正在组建问卷，请稍候
</div>


<script src="/framework/angular.min.js"></script>
<script src="/framework/restangular/restangular.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/framework/angular-toastr/angular-toastr.min.js"></script>
<script type="text/javascript" src="/framework/angular-toastr/angular-toastr.tpls.min.js"></script>
<script src="/system/service/common.js" type="text/javascript"></script>    

<script type="text/javascript" src="/framework/vue/zepto.min.js"></script>
<script src="/framework/lodash.min.js" type="text/javascript"></script>
<script src="/framework/vue/vue.min.js" type="text/javascript" ></script>
<!--<script src="https://cdn.bootcss.com/vConsole/3.3.0/vconsole.min.js"></script>-->
<script type="text/javascript">
var yuming ="";
try{
yuming = commonUrl;
}catch(e){
alert("ee");
}
//var vConsole = new VConsole();

  console.log('Hello world');
//手机判断
var browser = {
    versions: function () {
        var u = navigator.userAgent, app = navigator.appVersion;
        return {         //移动终端浏览器版本信息
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
            iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            wp: u.indexOf('IEMobile') > -1, //是否wp
            symbianos: !!u.match(/SymbianOS.*/), //是否SymbianOS
            webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
        };
    } (),
    language: (navigator.browserLanguage || navigator.language).toLowerCase()
}
 if ((browser.versions.iPhone || browser.versions.ios || browser.versions.iPad)&&QueryString("token")==undefined) {
    $("#appshow").show();
 }
var wenjuan ={};
var dati =[];
var user = {};//登录人信息，注意需要企业ID,组织架构ID
var vm;
var key = QueryString("key");
var xtype = QueryString("xtype");
var xid = QueryString("xid");
var type = QueryString("type");

//界面初始化
$(function(){

  if(key != null){
    user = GetlocalStorage("userinfo");
    if(QueryString("token")!=undefined&&QueryString("uid")!=undefined){
         SetlocalStorage("userinfo_token",{token:QueryString("token")});
        if(user==undefined||user==null||user.user_ID==undefined){
            getAjax(yuming+"/PersonnelManagement/PersonnelGetKey",{user_ID:QueryString("uid")},function(data){
                user=data.data;
                SetlocalStorage("userinfo",data.data);
                initQues();
            });
        }
    }else{
        initQues();
    }
    
  }
  else{
    alert("参数错误");
  }

});
function initQues(){
    getAjax(yuming+"/questionnaire/findTopicDetails",{qid:key,xtype:xtype,xid:xid,type:type},function(data){
      if(data.errorcode == "0"){
        wenjuan = data.data;
        wenjuan.question = JSON.parse(data.data.question);
       //wenjuan.qualified = JSON.parse(data.data.qualified);
        wenjuan.taglist = JSON.parse(data.data.taglist);
        wenjuan.result = JSON.parse(data.data.result);
        console.log(wenjuan.question);
        
        if(type==2){
            $(".weui-btn").remove();
            dati=data.data.question;
        }
        if(!wenjuan.login && user == null)//如果不能匿名，且未登录
        {
          window.location = "/index.html";
        }
        else{
          vmchushi();
          if(QueryString("b") != null){
            vm.baobiao = true;
          }
          $("#laod").hide();
        }
      }
      else{
        alert("读取错误"+data.errorcode);
      }
    });   
}
function vmchushi(){
	vm = new Vue({
		el: '#app',
  		data: {
  			wjobj:wenjuan,//题目对象
  			answer:dati, //答题记录
  			loading:false,
  			jieshu:false,
            baobiao:false//是否直接显示报表
  		
  		},
  		computed: {
  			sums(){//计算总分
  				var zongfen=0;
  				var qulist = this.answer;
  				for(var i=0;i<qulist.length;i++)
  				{
  					for(var j=0;j<qulist[i].group.length;j++)//循环得到每个题
	  				{
		  					for(var z=0;z<qulist[i].group[j].daan.length;z++)
		  					{
		  						zongfen = parseInt(zongfen)+parseInt(qulist[i].group[j].daan[z].defen);
		  					}
	  				}
  				}
  				return zongfen;
  			}
  		},
  		methods: {
        jindutiao:function(sel,qid){
          var qulist = this.wjobj.question;
          var qcount = 0;
          for(var i=0;i<qulist.length;i++)
          {
            for(var j=0;j<qulist[i].group.length;j++)//循环得到每个题
            {
              if(qulist[i].group[j].id==qid){
                for(var z=0;z<qulist[i].group[j].qselection.length;z++)
                {
                  qcount+=parseInt(qulist[i].group[j].qselection[z].selected);
                }
                break;
              }
            }
          }
          return qcount;
        },
  			answers:function(id1,id2,id3){//组的id ，题的id，选项的id
  				var alist= this.answer;
  				var youma = false;
                //这是新增的时候回显
                if(type==undefined||type==1){
  				    for(var i =0;i<alist.length;i++){
  					    if(alist[i].groupid == id1){
  						    for(var j =0;j<alist[i].group.length;j++){
  							    if(alist[i].group[j].qid == id2){
  								    for(var z=0;z<alist[i].group[j].daan.length;z++){
										    if(alist[i].group[j].daan[z].daanid == id3){
											    youma = true;
  										    }
  								    }
  							    }
  						    }
  					    }
  				    }
                }
  				return youma
  				//return this.answers;
  			},
  			tixingname:function(typeid){
  				if(typeid == 0)
  				{
  					return ". [单选题]";
  				}
  				else if(typeid == 1)
  				{
  					return ". [多选题]";
  				}
  				else if(typeid == 2)
  				{
  					return ". [问答题]";
  				}
  				else if(typeid == 3)
  				{
  					return ". [量表题]";
  				}
  				else{
  					console.log(typeid);
  					return "";
  				}
  			},
  			xuanze:function(groupid,qid,tixing,xuanxiang){
  				if(xuanxiang == undefined){
  					xuanxiang = {};
  					xuanxiang.id = "";
  					xuanxiang.tagid = null;
  					xuanxiang.score = 0;
  					xuanxiang.text = $("#text"+qid).val();
  				}
  				//console.log(xuanxiang.text);
  		
  				//return;
  				var alist= this.answer;
  				var zhaodao = false;
  				for(var i =0;i<alist.length;i++){
  					if(alist[i].groupid == groupid){
  						//找到历史数据
  						var zhaodao2 = false;
  						for(var j =0;j<alist[i].group.length;j++){
  							if(alist[i].group[j].qid == qid){
  								//找到了这个题目的答题记录
  								//如果为单选，则删除原来的，修改成现在的，
  								//如果为多选，则为增加或删除
  								if(tixing == 0 || tixing ==3){
  									var obj ={
											daanid:xuanxiang.id,//答案/选项ID
											tagid:xuanxiang.tagid,//维度ID
											daantext:"",//问答题答案
											defen:xuanxiang.score //答案得分
									};
  									alist[i].group[j].daan =[];//清空答案，阜新答案
  									alist[i].group[j].daan.push(obj);

  								}
  								else if(tixing == 1){
  									var zhaodao3= false;
  									for(var z=0;z<alist[i].group[j].daan.length;z++){
										if(alist[i].group[j].daan[z].daanid == xuanxiang.id){
												//已经存在了，删除掉
												alist[i].group[j].daan.splice(z,1);
												zhaodao3 = true;
  										}
  									}
  									if(zhaodao3 == false)
  									{
  										//插入
  										var obj ={
											daanid:xuanxiang.id,//答案/选项ID
											tagid:xuanxiang.tagid,//维度ID
											daantext:"",//问答题答案
											defen:xuanxiang.score //答案得分
										};
	  									alist[i].group[j].daan.push(obj);
  									}

  								}
  								else if(tixing == 2){
  									var obj ={
											daanid:xuanxiang.id,//答案/选项ID
											tagid:xuanxiang.tagid,//维度ID
											daantext:xuanxiang.text,//问答题答案
											defen:xuanxiang.score //答案得分
									};
  									alist[i].group[j].daan =[];//清空答案，阜新答案
  									alist[i].group[j].daan.push(obj);
  								}
  								else{
  									
  								}
  								zhaodao2 = true;
  							}
  							
  						}
  						
	  					if(zhaodao2 == false){
	  						//未找到答题记录
	  							var timu = {
									qid:qid,//题目ID
									tixing:tixing,//题型
									daan:[
										{
											daanid:xuanxiang.id,//答案/选项ID
											tagid:xuanxiang.tagid,//维度ID
											daantext:xuanxiang.text,//问答题答案
											defen:xuanxiang.score //答案得分
										}
									]
								};
								alist[i].group.push(timu);
	  					
	  					}
  						zhaodao = true;
  					}
  					
  				}


  				if(zhaodao == false){
  					//没找到，新建
  					var obj = {groupid:groupid,//组ID
								group:[]};
					var timu = {
						qid:qid,//题目ID
						tixing:tixing,//题型
						daan:[
							{
								daanid:xuanxiang.id,//答案/选项ID
								tagid:xuanxiang.tagid,//维度ID
								daantext:xuanxiang.text,//问答题答案
								defen:xuanxiang.score //答案得分
							}
						]
					};
					obj.group.push(timu);
					this.answer.push(obj);
  				}
  			},


  			sumberjuan:function(){//提交问卷

            //验证必做题目是否重复
              //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
              for(var i=0;i< this.wjobj.question.length;i++)
              {
                  //console.log(JSON.stringify(this.wjobj.question[i].group));
                 for(var j=0;j<this.wjobj.question[i].group.length;j++)
                 {
                    if(this.wjobj.question[i].group[j].qmust)
                    {
                      var bxid = this.wjobj.question[i].group[j].id;
                      var strobj = JSON.stringify(dati);
                      if(strobj.indexOf(bxid) <0)
                      {
                        alert("第"+(i+1)+"组第"+(j+1)+"题为必选题目,还请作答！");
                        return false;
                      }
                      //console.log();
                    }
                 }
              }

             // console.log(JSON.stringify(this.wjobj));
              if(dati.length == 0)
              {
                  alert("您还没有作答噢！");
              }

  				var canshu ={questionnaireId:wenjuan.id,dati:JSON.stringify(dati),xtype:xtype,xid:xid};
          console.log(canshu);
  				if(user != null){
  					canshu.userid =user.user_ID;// user.user_ID;
  				}
          //console.log(this.wjobj);;


          //this.jieshu = true;
          //return;
          var that = this;

          console.log(this.wjobj);
          
       // return;
			  	getAjax(yuming+"/questionnaire/saveTopicUser",canshu,function(data){
					if(data.errorcode == "0"){
						if(that.wjobj.type ==0){
			  				if(that.wjobj.jieguo){
			  					//跳转问卷结果界面
                alert("提交成功");
                that.baobiao = true;
			  				}else{
			  					//提示问卷提交成功
			  					that.jieshu = true;

			  				}
			  			}else if(that.wjobj.type ==1){
			  				that.wjobj.end = that.wjobj.end+ "<br />合格分数："+that.wjobj.qualified ==null ?"0":that.wjobj.qualified0.min+"<br /> 评估获得："+that.sums;
			  				that.jieshu = true;
			  			}else if(that.wjobj.type ==2){
			  				that.jieshu = true;
			  			}else{
                            
			  			}
			  		}else if(data.errorcode=="71"){
						alert("您已经答过该问卷了，请不要重复作答！");
					}else{
						alert("错误"+data.errorcode);
					}
				});
  			},

  		},//注册函数
  		directives:{//注册指令
  			
  		}
	});
}

//用于生成uuid
function guid() {
	function S4() {
	    return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
	}
	 return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
/**
  *工具 || 获得URL GET参数
 */
function QueryString(fieldName) {
    /// <summary>
    ///   获得URL GET参数
    /// </summary>
    /// <param name="fieldName" type="String">
    ///   参数名
    /// </param>
    /// <returns type="void" />如果不存在返回NULL
    var reg = new RegExp("(^|&)" + fieldName.toLowerCase() + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}
//**********************************************************************
//全局异步请求数据
//**********************************************************************
document.writeln("<div id=\'loadingToast\' style=\'display:none;\'>");
document.writeln("        <div class=\'weui-mask_transparent\'></div>");
document.writeln("        <div class=\'weui-toast\'>");
document.writeln("            <i class=\'weui-loading weui-icon_toast\'></i>");
document.writeln("            <p class=\'weui-toast__content\'>数据加载中</p>");
document.writeln("        </div>");
document.writeln("    </div>");
function getAjax(url, parm, callBack, callBackError, callBackType, mode, istongbu) {
    $("#loadingToast").show();
    var token = "userinfo_token is none";
    if (callBackType == null || callBackType == "" || callBackType == undefined)
        callBackType = "text";
    if (mode == null || mode == "" || mode == undefined)
        mode = "post";
    if (istongbu != undefined && !istongbu) {
        istongbu = false;
    } else {
        istongbu = true;
    }
    try {
        $.ajax({
            type: mode,
            beforeSend: function (xhr) {
                    token = strToJson(GetlocalStorage("userinfo_token"));
                    xhr.setRequestHeader("X-Session-Token", token.token);
            },
            //手机端需要加上token验证
            headers: {
                //"Accept": "text/plain; charset=utf-8",
                //"Content-Type": "text/plain; charset=utf-8",
                "Accept": "application/json, text/javascript, */*; charset=utf-8",
                "Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
            },
            async: istongbu,
            url: url,
            data: parm,
            dataType: callBackType,
            cache: false,
            success: function (msg, status, xhr) {
                pedding = false;
                $("#loadingToast").hide();
                msg = strToJson(msg);
                if (msg && msg.errorcode && (msg.errorcode == 35 || msg.errorcode == 36)) {
                    alert("身份验证已失效，请重新登录！");
                } else {
                    callBack(msg);
                    //  console.log(msg);
                }
            },
            error: function (err) {
                // $.hideIndicator(); //loading
                if (callBackError != undefined && callBackError != null && callBackError != "")
                    callBackError(err);
                // $.alert(err);
                console.log('请求服务器错误！');
                pedding = false;
                console.error("服务器访问异常：" + err.readyState);
                $("#loadingToast").hide();
            }
        });

    }
    catch (error) {
        console.log(error);
        alert("请求错误,请刷新重试！");
        $("#loadingToast").hide();
    }
}
/**
* 工具 || 获得本地存储
*/
function GetlocalStorage(name) {
    // / <summary>
    // / 获得本地数据
    // / </summary>
    if (window.localStorage) {
        var value = localStorage.getItem(name);
        if (value != null) {
            return JSON.parse(value);
        } else {
            return value;
        }
    } else {
        alert("您需要升级浏览器");
    }
}
/**
*工具 || 存储
*/
function SetlocalStorage(name, obj) {
    // / <summary>
    // / 重写本地数据
    // / </summary>
    if (window.localStorage) {
        try {
            localStorage.setItem(name, JSON.stringify(obj));
        }
        catch (oException) {
            if (oException.name == 'QuotaExceededError') {
                console.log('超出本地存储限额！');
                //如果历史信息不重要了，可清空后再设置
                localStorage.clear();
                localStorage.setItem(name, JSON.stringify(obj));
            }
        }
    } else {
        alert("您需要升级浏览器才能够进行学习");
    }
}
//字符转对象
function strToJson(str) {
    try {
        if (str != null && str != "" && str != undefined) {
            return JSON.parse(str);
        } else {
            return null;
        }
    } catch (e) {
        return str;
    }
}
</script>
</body>
</html>